using System;
using System.IO;
using System.Xml;
using System.Text;
namespace Microsoft.Health.Samples.PatientConnect.TreyResearch.HealthVaultAdapter
{
    /// <summary>
    /// Class handles database operations for application
    /// </summary>
    public static class ClinicalDataBaseManager
    {
        private const string _dateformat = "yyyyMMddThhmmss";
        private const string _fileExtension = ".xml";

        /// <summary>
        /// Creates XmlDataBase for new Patient
        /// </summary>
        /// <param name="practiceFolderPath">Practice folder path</param>
        /// <param name="personId">PersonId</param>
        /// <param name="sampleCcrCcdFolderPath">Sample CCRCCD folder path</param>
        /// <param name="hl7MessageFolderPath">sample HL7 Message Folder path</param>
        public static void CreateXmlDataBase(string practiceFolderPath,
                                             string personId,
                                             string sampleCcrCcdFolderPath,
                                             string hl7MessageFolderPath)
        {


            string medicationFilePath = string.Format(@"{0}\{1}\Medication-{2}-{3}{4}",
              practiceFolderPath, Constants.MedicationFolderName, personId, DateTime.Now.ToString(_dateformat), _fileExtension);

            string labTestResultFilePath = string.Format(@"{0}\{1}\HL7LabTest-{2}-{3}{4}",
                practiceFolderPath, Constants.LabResultsFolderName, personId, DateTime.Now.ToString(_dateformat), _fileExtension);

            string ccrFilePath = string.Format(@"{0}\{1}\ASTMCCR-{2}-{3}{4}",
                            practiceFolderPath, Constants.CcrFolderName, personId, DateTime.Now.ToString(_dateformat), _fileExtension);

            string ccdFilePath = string.Format(@"{0}\{1}\HL7CCD-{2}-{3}{4}",
                            practiceFolderPath, Constants.CcdFolderName, personId, DateTime.Now.ToString(_dateformat), _fileExtension);

            using (XmlTextWriter xmlWriter = new XmlTextWriter(medicationFilePath.ToString(), Encoding.UTF8))
            {
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("Medications");
                xmlWriter.WriteEndElement();
                xmlWriter.Close();
            }

            XmlDocument xmlDoc;
            xmlDoc = new XmlDocument();
            xmlDoc.Load(Path.Combine(sampleCcrCcdFolderPath, Constants.SampleCcdFileName));
            xmlDoc.Save(ccdFilePath);

            xmlDoc = new XmlDocument();
            xmlDoc.Load(Path.Combine(sampleCcrCcdFolderPath, Constants.SampleCcrFileName));
            xmlDoc.Save(ccrFilePath);

            HL7MessageParser hl7Parser = new HL7MessageParser();
            XmlDocument hl7Doc = hl7Parser.ParseFile(Path.Combine(hl7MessageFolderPath, Constants.SampleHL7MessageFileName));

            LabResults labresultthingtype = new LabResults();
            labresultthingtype.CreateLabResult(labTestResultFilePath, hl7Doc);
        }

        /// <summary>
        /// create new patient and adds in the database
        /// </summary>
        /// <param name="patientFilePath">patient file path</param>
        /// <param name="lastName">Last name</param>
        /// <param name="firstName">First name</param>
        /// <param name="middleName">Middle name</param>
        /// <returns>patient Id respective to database</returns>
        public static string CreatePatient(string patientFilePath,
                                           String lastName,
                                           String firstName,
                                           String middleName)
        {
            Patient newPatient = new Patient(patientFilePath);
            newPatient.PatientId = Guid.NewGuid();
            newPatient.MedicalRecordNumber = Guid.NewGuid().ToString();
            newPatient.LastName = lastName;
            newPatient.FirstName = firstName;
            newPatient.MiddleName = middleName;
            newPatient.Active = true;
            newPatient.RegisteredWithHealthVault = false;
            newPatient.AddPatient();
            return newPatient.PatientId.ToString();
        }

        /// <summary>
        /// Create Database Directories for the new practice
        /// </summary>
        /// <param name="folderPath">Practice folder path</param>
        public static void CreateDataBaseDirectories(string folderPath)
        {
            string parentDirectoryPath = string.Empty;
            parentDirectoryPath = folderPath;

            Directory.CreateDirectory(parentDirectoryPath);

            CreatePatientXmlFile(Path.Combine(parentDirectoryPath, Constants.PatientXmlFileName));

            Directory.CreateDirectory(Path.Combine(parentDirectoryPath, Constants.CcdFolderName));

            Directory.CreateDirectory(Path.Combine(parentDirectoryPath, Constants.CcdFolderName + @"\" + Constants.UploadedFolderName));

            Directory.CreateDirectory(Path.Combine(parentDirectoryPath, Constants.CcrFolderName));
            Directory.CreateDirectory(Path.Combine(parentDirectoryPath, Constants.CcrFolderName + @"\" + Constants.UploadedFolderName));

            Directory.CreateDirectory(Path.Combine(parentDirectoryPath, Constants.LabResultsFolderName));
            Directory.CreateDirectory(Path.Combine(parentDirectoryPath, Constants.LabResultsFolderName + @"\" + Constants.UploadedFolderName));

            Directory.CreateDirectory(Path.Combine(parentDirectoryPath, Constants.MedicationFolderName));
        }

        /// <summary>
        /// Creates patient file for new practice
        /// </summary>
        /// <param name="patientFilePath">patient file path</param>
        private static void CreatePatientXmlFile(string patientFilePath)
        {
            using (XmlTextWriter xmlWriter = new XmlTextWriter(patientFilePath, Encoding.UTF8))
            {
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("Patients");
                xmlWriter.WriteEndElement();
                xmlWriter.Close();
            }
        }

        /// <summary>
        /// Creates new practice and adds in the database
        /// </summary>
        /// <param name="practiceFilePath"></param>
        /// <param name="applicationId"></param>
        /// <param name="providerName"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public static void CreateNewPractice(string practiceFilePath,
                                            Guid applicationId,
                                            string providerName,
                                            string userName,
                                            string password)
        {
            Practice providerPractice = new Practice(practiceFilePath);
            providerPractice.PracticeName = providerName;
            providerPractice.PracticeId = Guid.NewGuid();
            providerPractice.ChildAppId = applicationId;
            providerPractice.DataFolder = "Practice-Dr. " + providerName;
            providerPractice.AddPractice();

            //Add user to respective Practice

            Users users = new Users(practiceFilePath);
            users.UserId = Guid.NewGuid();
            users.UserName = userName.Trim();
            users.Password = password.Trim();
            users.PracticeId = providerPractice.PracticeId;
            users.AddUser();
        }
    }
}
